<template>
  <div class="w-[98%] p-20px">
    <div style="margin-bottom: 10px">

      <el-select style="width: 130px" v-model="filter.type" placeholder="优先级" clearable>
        <el-option v-for="item in getEnumBySn('priority')" :label="item.label" :key="item.value"
                   :value="item.value"></el-option>
      </el-select>

      <el-select style="width: 130px;margin-left: 10px" v-model="filter.sex" placeholder="性别" clearable>
        <el-option label="男" value="男"></el-option>
        <el-option label="女" value="女"></el-option>
      </el-select>

      <el-select style="width: 130px" v-model="filter.status" placeholder="处理状态" clearable>
        <el-option v-for="item in getEnumBySn('maintenanceStatus')" :label="item.label" :key="item.value"
                   :value="item.value"></el-option>
      </el-select>

      <el-select style="width: 180px" v-model="filter.handleUser" placeholder="处理人" clearable filterable>
        <el-option v-for="item in groupList" :label="item.label" :key="item.value"
                   :value="item.value"></el-option>
      </el-select>

      <el-input style="width: 130px;margin-left: 10px" v-model="filter.customName" placeholder="客户姓名"></el-input>

      <el-select style="width: 120px" v-model="filter.indexId" clearable filterable placeholder="合作编号">
        <el-option v-for="item in agencyList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>

      <el-select v-model="filter.trusteeshipType" required style="width: 130px;margin-left: 10px" clearable
                 placeholder="年/月">
        <el-option v-for="item in getEnumBySn('cycleTypeEnum')" :label="item.label" :key="item.value"
                   :value="item.value"></el-option>
      </el-select>


      <el-select v-model="filter.platformType" required style="width: 130px" clearable
                 placeholder="平台类型">
        <el-option v-for="item in getEnumBySn('daikuanTypeEnum')" :label="item.label" :key="item.value"
                   :value="item.value"></el-option>
      </el-select>

      <el-select style="width: 130px;margin-left: 10px" v-model="filter.comePhone" placeholder="进线手机号" clearable filterable>
        <el-option v-for="item in phoneList" :label="item.label" :key="item.value"
                   :value="item.value"></el-option>
      </el-select>

      <el-select style="width: 130px;margin-left: 10px" v-model="filter.phoneNo" placeholder="转接手机号" clearable filterable>
        <el-option v-for="item in phoneList" :label="item.label" :key="item.value"
                   :value="item.value"></el-option>
      </el-select>



      <el-input style="width: 130px;margin-left: 10px" v-model="filter.platform" placeholder="平台"></el-input>




      <el-date-picker
        style="width: 220px;margin-left: 10px"
        v-model="filter.createDateTimeRange"
        type="daterange"
        range-separator="到"
        start-placeholder="派单日期"
        end-placeholder="派单日期"
        value-format="YYYY-MM-DD"
      />
      <el-date-picker
        style="width: 220px;margin-left: 10px"
        v-model="filter.lastHandleTimeRange"
        type="daterange"
        range-separator="到"
        start-placeholder="最后处理日期"
        end-placeholder="最后处理日期"
        value-format="YYYY-MM-DD"
      />

      <el-button type="primary" @click="fetchData">查询</el-button>

<!--      <el-select v-model="filter.typeName" required style="width: 130px;margin-left: 10px" clearable-->

<!--      <el-select v-model="filter.trusteeshipType" required style="width: 130px;margin-left: 10px" clearable-->
<!--        placeholder="托管类型">-->
<!--        <el-option v-for="item in getEnumBySn('cycleTypeEnum')" :label="item.label" :key="item.value"-->
<!--          :value="item.value"></el-option>-->
<!--      </el-select>-->
<!--      <el-input style="width: 130px;margin-left: 10px" v-model="filter.platform" placeholder="处理平台"></el-input>-->
<!--      <el-input style="width: 130px;margin-left: 10px" v-model="filter.weihushoujihao" placeholder="维护手机号"></el-input>-->
    </div>


    <el-table :data="tableData" style="width: 100%" border stripe>
      <el-table-column label="序号" width="60" align="center">
        <template #default="{ $index }">
          {{ $index + 1 }} <!-- 使用 $index 计算序号 -->
        </template>
      </el-table-column>
      <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
        :width="column.width"  :align="column.align" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template v-slot="scope">
          <el-button @click="editHandle(scope.row)" size="mini" type="primary">编辑</el-button>
          <el-button type="danger" @click="deleteHandle(scope.row)" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination :current-page="currentPage" :page-size="pageSize" :total="totalItems" @current-change="currentChange"
      background layout="total,prev, pager, next" class="pagination" prev-text="上一页" next-text="下一页"></el-pagination>
    <Modal ref="modalRef" @ok="okHandle" />
  </div>
  <PageNoteDetail height="100px" id="1929442914709229570"></PageNoteDetail>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import Modal from "./modal.vue"
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/config/axios'
import {getEnumBySn, getIndexIdList, getPhoneList, groupList} from "@/api/enums";
import PageNoteDetail from "@/views/tool/PageNote/PageNoteDetail.vue";

const filter = ref({
  status: '',
  handleUser: '',
  customName: '',
  sex: '',
  platform: '',
  comePhone: '',
  createDateTimeRange: [],
  lastHandleTimeRange: []
});
const modalRef = ref();

const phoneList = ref()

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 节流函数
const throttle = (fn, delay) => {
  let lastTime = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastTime >= delay) {
      fn.apply(this, args);
      lastTime = now;
    }
  };
};

// 使用节流包装 fetchData
const throttledFetchData = throttle(fetchData, 1000);

// 监听 filter 对象的变化
watch(
  () => ({ ...filter.value }), // 创建新对象以触发深度监听
  debounce((newVal, oldVal) => {
    throttledFetchData();
  }, 500),
  { deep: true }
);

const tableData = ref([
  {
    orderStatus: '托管',
  }
])


const columns = ref([
  {prop: 'handleUser', label: '处理人', width: '70', align: 'center'},
  {prop: 'typeName', label: '优先级', width: '80', align: 'center'},
  {prop: 'customName', label: '客户姓名', width: '90', align: 'center'},
  {prop: 'agencyName', label: '合作编号', width: '90', align: 'center'},
  {prop: 'trusteeshipType', label: '年/月', width: '60', align: 'center'},
  {prop: 'platformType', label: '平台类型', width: '90', align: 'center'},
  {prop: 'platform', label: '平台', width: '100', align: 'center'},
  {prop: 'trusteeshipAmount', label: '金额', width: '90', align: 'center'},
  {prop: 'handleReason', label: '处理原因', width: '90', align: 'center'},
  {prop: 'handleMemo', label: '备注', width: '150', align: 'center'},
  {prop: 'status', label: '处理状态', width: '90', align: 'center'},
  { prop: 'handleProgress', label: '处理进度', width: '90',align:'center' },
  {prop: 'createDateTime', label: '创建时间', width: '120', align: 'center'},
  {prop: 'lastHandleTime', label: '最后处理时间', width: '120', align: 'center'},
  {prop: 'phoneNo', label: '转接手机号', width: '150', align: 'center'},
  {prop: 'comePhoneCode', label: '进线手机号', width: '150', align: 'center'},
]);

const totalItems = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const currentItem = ref({});

const currentChange = (v) => {
  currentPage.value = v
  fetchData()
}

async function fetchData() {
  const response = await request.get({
    url: '/maintenance/list',
    params: {
      ...filter.value,
      createDateTimeStart: filter.value.createDateTimeRange?.[0],
      createDateTimeEnd: filter.value.createDateTimeRange?.[1],
      lastHandleTimeStart: filter.value.lastHandleTimeRange?.[0],
      lastHandleTimeEnd: filter.value.lastHandleTimeRange?.[1],
      current: currentPage.value,
      orderStatusList: ['处理中','定期维护','CCC待换转移','DDD待关转移有群','EEE有群待解散','FFF彩铃未关']
    }
  })
  let dictMap = {}
  let enumBySn = getEnumBySn('priority');
  //转换正
  enumBySn.forEach(item => {
    dictMap[item.value] = item.label;
  })
  tableData.value = response.records?.map(item => {
    item.typeName = dictMap[item.type]
    return item;
  })
  totalItems.value = response.total
  currentPage.value = response.current
}

const okHandle = () => {
  fetchData()
}

const editHandle = (rowData) => {
  modalRef.value?.edit(rowData)
  currentItem.value = rowData
}

const agencyList = ref([])
getIndexIdList().then(res => {
  agencyList.value = res;
})

const deleteHandle = function (row) {
  ElMessageBox.confirm('确定要删除这条记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    request.delete({
      url: "/maintenance/deleteById",
      params: {
        id: row.id
      }
    }).then(() => {
      ElMessage.success("删除成功!")
      fetchData()
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
onMounted(() => {
  fetchData(); //获取列表
  getPhoneList().then(res => {
    phoneList.value = res.filter(item => !item.label?.startsWith("000"));
  })
  // fetchEnumList() // 获取下拉列表
});
</script>

<style scoped>
.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter-section>* {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  float: right;
  font-size: 22px;
}

.drawer-footer {
  text-align: right;
  margin-top: 20px;
}

.form-inline {
  display: flex;
  flex-wrap: wrap;
}

.form-inline .el-form-item {
  margin-right: 20px;
}
</style>
